//
//  BookDetailPhotosController.m
//  FreeTrip
//
//  Created by lanou on 15/11/27.
//  Copyright © 2015年 邓芮. All rights reserved.
//

#import "BookDetailPhotosController.h"
#import "PhotosModel.h"
#import "ImageCell.h"
#import "WateFlowlayout.h"
#import "PhotoViewController.h"
#define  Kurl @"http://chanyouji.com/api/attractions/photos/%ld.json?page=%ld"
@interface BookDetailPhotosController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateWaterFlowLayout>

@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) WateFlowlayout *layout;
@property (nonatomic, assign) NSInteger moreNum;//加载更多


@end

static NSString *cellIdentifier = @"cell";
@implementation BookDetailPhotosController

- (NSMutableArray *)modelArray
{
    if (!_modelArray)
    {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //[self networkRequestWithUrl:@"http://chanyouji.com/api/attractions/photos/35443.json?page=1"];
    self.moreNum = 1;
    [self networkRequestWithUrl:[NSString stringWithFormat:Kurl,(long)_Id,(long)_moreNum]];
    
    
    WateFlowlayout *layout = [[WateFlowlayout alloc] init];
    layout.itemSize = CGSizeMake((KScreenWidth - 25) /2, 0);
    layout.sectionInsets = UIEdgeInsetsMake(0, 10, 5, 10);
    layout.numberOfColumns = 2;
    layout.interitemSpacing= 5;
    layout.delegate = self;
    //self.layout = layout;
    
//    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//    layout.itemSize = CGSizeMake(100, 100);
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[ImageCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];
    
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        self.moreNum = self.moreNum + 1;
        [self networkRequestWithUrl:[NSString stringWithFormat:Kurl,(long)_Id,(long)self.moreNum]];
        [self.collectionView.mj_footer endRefreshing];
    }];
    
     self.collectionView.mj_footer = footer;
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self networkRequestWithUrl:[NSString stringWithFormat:Kurl,(long)_Id,(long)self.moreNum]];
        [self.collectionView.mj_header endRefreshing];
    }];
    
}


#pragma mark   ---数据请求----
- (void)networkRequestWithUrl:(NSString *)url
{
    [[NetworkState shareInstance] reachablityStates:self];
    
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"加载失败");
            return ;
        }
        
       
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        for (NSDictionary *firDic in array)
        {
            PhotosModel *model = [[PhotosModel alloc] init];
            [model setValuesForKeysWithDictionary:firDic];
            [self.modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^
        {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self.collectionView reloadData];
        });
        
        
    }]resume];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
//    if(_modelArray.count !=0)
//    {
//    return 1;
//    }
//    else
//    {
//        return 0;
//    }
    return 1;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.modelArray.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    PhotosModel *model = self.modelArray[indexPath.row];
    cell.imageView.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() %256 / 255.0 blue:arc4random()% 256 / 255.0 alpha:1.0];
    //cell.imageView.backgroundColor = [UIColor redColor];
    
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.image_url]];
    
    
    return cell;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView waterFlowLayout:(WateFlowlayout *)layout heightForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotosModel *model = self.modelArray[indexPath.row];
    CGFloat itemHeith = 145 * model.image_height / model.image_width;
    
//    NSLog(@"%f", itemHeith);
    return itemHeith;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSInteger num = indexPath.row;
    PhotoViewController *photoVc = [[PhotoViewController alloc] init];
    photoVc.modelArray = self.modelArray;
    photoVc.item = num;
    [self presentViewController:photoVc animated:YES completion:nil];
    
    
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
